<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\Annual;
use app\admin\model\Data as DataModel;
use app\admin\model\Match as MatchModel;
use app\admin\model\DataClass;
use app\admin\model\DataClasses;
use app\admin\model\DataProf;
use app\admin\model\SportRecord;
use app\admin\model\Sport;
use app\admin\service\GradeService;
use app\admin\service\DepartmentsService;
use think\Db;


/**
 * 系统登录-控制器
 * @author 牧羊人
 * @since 2020/11/19
 * Class WechatminiLogin
 * @package app\admin\controller
 */
class Led extends Backend
{
    /**
     * 初始化
     * @author 牧羊人
     * @since 2020/11/19
     */
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new Sport();
        $this->annualModel = new Annual();
    }

    public function school_a(){
        $data = json_decode(file_get_contents('https://apitiyu.bigchun.com/test.json'),true);
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $data,
        );
        return $this->jsonReturn($message);
    }
    //学校画像
    //数据中心
    public function school()
    {
        //计算BIM
        //$map1[] = ['itemCode','=','weight'];

        //echo $list;
        //die();
        $s = microtime(true);
        $param      = request()->param();
        $canyu_rate = DataModel::ticeren() / \app\admin\model\Memb::allNum();

        $canyu_rate = pro_float($canyu_rate) * 100;
        $hege      = DataModel::ticerenHege();
        $hege_rate = 0;
        if ($hege > 0) {
            $hege_rate = $hege / DataModel::ticeren();
            $hege_rate = round($hege_rate * 100, 2) . '%';
        }
        $yuanhegelv  = DataModel::xueyuanArrList();
        $yuanservies = $yuanhegelv[1];
        // halt($yuanservies);
        $youxiu   = $yuanservies[0];
        $lianghao = $yuanservies[1];
        $hege     = $yuanservies[2];
        $youxiu1  = array_filter(
            $youxiu['data'],
            function ($value) {
                return intval($value) > 0;
            }
        );
        foreach ($youxiu1 as $key => $value) {
            $youxiu1[$key] = floatval($value);
        }
        // halt($youxiu1);
        if (array_sum($youxiu1) > 0 || count($youxiu1) > 0) {
            $youxiulv = intval(array_sum($youxiu1) / count($youxiu1)) . '%';
        } else {
            $youxiulv = '0%';
        }
        $lianghao1 = array_filter(
            $lianghao['data'],
            function ($value) {
                return intval($value) > 0;
            }
        );
        foreach ($lianghao1 as $key => $value) {
            $lianghao1[$key] = floatval($value);
        }

        if (array_sum($lianghao1) > 0 || count($lianghao1) > 0) {
            $lianghaolv = intval(array_sum($lianghao1) / count($lianghao1)) . '%';$s = microtime(true);
        } else {
            $lianghaolv = '0%';
        }

        $hege1 = array_filter(
            $hege['data'],
            function ($value) {
                return intval($value) > 0;
            }
        );
        foreach ($hege1 as $key => $value) {
            $hege1[$key] = floatval($value);
        }

        if (array_sum($hege1) > 0 || count($hege1) > 0) {
            $hegelv = intval(array_sum($hege1) / count($hege1)) . '%';
        } else {
            $hegelv = '0%';
        }

        $canyulv     = DataModel::projectArrList();
        $canyulvlist = array_map(
            function ($a, $b) {
                return array('name' => $a, 'value' => $b);
            },
            $canyulv[0],
            $canyulv[1]
        );
        $high_weight = DataModel::xueyuanBmi();
        //print_r($high_weight);die();
        $levelData = DataModel::levelAvg2();
        //$man_level       = DataModel::levelAvg();
        $man_level       = [$levelData['list'], $levelData['data'][1]];
        //$woman_level     = DataModel::levelAvg(2);
        $woman_level     = [$levelData['list'], $levelData['data'][2]];
        $yundongshichang = DataModel::ydshichang();
        $yundonglist     = [];
        $color           = [
            '#f845f1',
            '#ad46f3',
            '#5045f6',
            '#4777f5',
            '#44aff0',
            '#45dbf7',
            '#f6d54a',
            '#f69846',
            '#ff4343'
        ];
        foreach ($yundongshichang as $k => $val) {
            $arr              = [];
            $arr['value']     = number_format($val['views'], 2);
            $arr['name']      = $val['time'];
            $arr['itemStyle'] = ['normal' => ['color' => $color[($k + 1) % 9]]];
            $yundonglist[]    = $arr;
        }

        // todo 排名 姓名 学籍号 成绩 项目 班级 学院 年级
        $map  = [];
        $map2 = [];
        $sort = 'pingscore desc';
        // 赛事
        if (isset($param['taskId']) && (int)$param['taskId']) {
            $map[]  = ['taskId', '=', $param['taskId']];
            $map[]  = ['type', '=', 3];
            $map2[] = ['type', '=', 4];
        } else {
            $map[] = ['itemCode', '=', 'run-exercise'];
        }
        // 学年
        if (isset($param['gradeId']) && $param['gradeId']) {
            $map[] = ['gradeId', '=', $param['gradeId']];
        }

        // 院系
        if (isset($param['departmentsId']) && $param['departmentsId']) {
            $map[] = ['departmentsId', '=', $param['departmentsId']];
        }

        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        if (isset($param['taskId']) && $param['taskId'] > 0) {
            $result = $this->model->where($map)->order($sort)->page(0, 100)->column("id");
            $match  = [];
            if (count($result) > 200) {
                if (is_array($result)) {
                    foreach ($result as $k => $val) {
                        $info          = $this->model->getInfo($val);
                        $info['index'] = $k + 1;
                        $match[]       = $info;
                    }
                }
            } else {
                $match = Db::name('ledtest')->select();
                foreach ($match as $key => &$val) {
                    $val['index'] = $key + 1;
                }
                unset($val);
            }
        } else {
            $result = $this->model->where($map)->field('*,SUM(score) as total_score')->group('memberId')->order(
                'total_score',
                'desc'
            )->page(0, 100)->select();
            $match  = [];
            foreach ($result as $k => $val) {
                $info          = $this->model->getInfo($val['id']);
                $info['score'] = $val['total_score'];
                $info['index'] = $k + 1;
                $match[]       = $info;
            }
        }
//        echo '$result => ' . (microtime(true) - $s) . "\n";$s = microtime(true);

        // 设置查询条件
        $tice = [];
//        todo 前端应该没用,先注释
//        if (is_array($map2)) {
//            $map2[] = ['mark', '=', 1];
//        } elseif ($map2) {
//            $map2 .= " AND mark=1 ";
//        } else {
//            $map2 .= " mark=1 ";
//        }
//        if (isset($param['taskId']) && $param['taskId'] > 0) {
//            $result2 = $this->model->where($map2)->order($sort)->page(0, 100)->column("id");
//            $tice    = [];
//            if (count($result2) > 200) {
//                if (is_array($result2)) {
//                    foreach ($result2 as $k => $val) {
////                        $info          = $this->model->getInfo($val);
//                        $info['index'] = $k + 1;
//                        $tice[]        = $info;
//                    }
//                }
//            } else {
//                $tice = Db::name('ledtest')->select();
//                foreach ($tice as $key => &$val) {
//                    $val['index'] = $key + 1;
//                }
//                unset($val);
//            }
//        } else {
//            $result2 = $this->model->where($map2)->field('*,SUM(score) as total_score')->group('memberId')->order(
//                'total_score',
//                'desc'
//            )->page(0, 100)->select();
//            $tice    = [];
//            foreach ($result2 as $k => $val) {
////                $info          = $this->model->getInfo($val['id']);
//                $info['score'] = $val['total_score'];
//                $info['index'] = $k + 1;
//                $tice[]        = $info;
//            }
//        }
//        echo '$result2 => ' . (microtime(true) - $s) . "\n";$s = microtime(true);

        $memTotal = \app\admin\model\Memb::genderTotal();

        $scoreAggData = SportRecord::where('mark',1)
            ->whereNotNull('pingscore')
            ->fieldRaw('avg(pingscore) avg, max(pingscore) max, min(pingscore) min')
            ->cache(true,140)
            ->find();
        $s = microtime(true);
        $data = [
            //学校总人数
            "man_num"         => $memTotal[1] ?? 0,
            'women_num'       => $memTotal[2] ?? 0,
            //参与体测人数
            'canyu_num'       => DataModel::ticeren(),
            'canyu_rate'      => $canyu_rate . '%',
            //院系成绩合格率
            'youxiulv'        => $youxiulv,
            'lianghaolv'      => $lianghaolv,
            'hegelv'          => $hegelv,
            //体测合格率
            'hege_num'        => DataModel::ticerenHege(),
            'hege_rate'       => $hege_rate,
            //体测平均分
            'avg_num'         => $scoreAggData['avg'] ?? 0,
            'max_avg'         => $scoreAggData['max'] ?? 0,
            'mix_avg'         => $scoreAggData['min'] ?? 0,
            //学院
            'xueyuan'         => DataModel::xueyuan(),
            //各院系成绩合格率
            'hegedlv'         => [
                'data'   => $yuanhegelv[0],
                'series' => $yuanhegelv[1]
            ],
            //项目参与率
            'canyulv'         => [
                'data' => $canyulvlist,
            ],
            //运动时长
            'yundongshichang' => $yundonglist,
            // 各院系平均分
            'yuanxi_avgs'     => DataModel::yuanxiAvg(),
            //身高体重BMI
            'high_weight'     =>
                [
                    'xueyuan' => $high_weight[0],
                    'weight'  => $high_weight[1],
                    'high'    => $high_weight[2],
                ],
            //bmi计算，算出这批学生的平均身高和体重，根据平均身高和体重，计算出BMI，然后再计算出BMI的显示比例
            'weight'          => [
                ['value' => 111, 'name' => '偏瘦',],
                ['value' => 648, 'name' => '正常',],
                ['value' => 648, 'name' => '超重',],
                ['value' => 33, 'name' => '肥胖',],
            ],
            //男生
            'weight_man'      => [
                ['value' => 648, 'name' => '偏瘦',],
                ['value' => 22, 'name' => '正常',],
                ['value' => 648, 'name' => '超重',],
                ['value' => 33, 'name' => '肥胖',],
            ],
            //女生
            'weight_woman'    => [
                ['value' => 648, 'name' => '偏瘦',],
                ['value' => 22, 'name' => '正常',],
                ['value' => 648, 'name' => '超重',],
                ['value' => 6118, 'name' => '肥胖',],
            ],
            //各院系项目等级
            'project_level'   => DataModel::projectLevel(),
            //男生各项目平均分与等级
            'man_level'       =>
                [
                    'project' => $man_level[0],
                    'data'    => $man_level[1]
                ],
            //女生各项目平均分与等级
            'woman_level'     =>
                [
                    'project' => $woman_level[0],
                    'data'    => $woman_level[1]
                ],
            'match'           => $match,
            'tice'            => $tice,
        ];
        //返回结果
        $message = array(
            "msg"  => '操作成功',
            "code" => 0,
            "data" => $data,
        );

        return $this->jsonReturn($message);
    }

    public function getMatchList()
    {
        $result = [];
        $map = [
            'mark' =>1,
        ];
        $input = input();
        $map['mtype'] = isset($input['mtype'])?$input['mtype']:1;
        //print_R($map);
        $result = MatchModel::where($map)->field('id,name')->select();
        return $this->jsonReturn(message('成功',true,$result));
    }

    public function getGradeList()
    {
        $gradeservice = new GradeService();
        $result = $gradeservice->getGradeList();
        return $this->jsonReturn($result);
    }

    public function getDepartmentsList()
    {
        $Departmentservice = new DepartmentsService();
        $result = $Departmentservice->getDepartmentsList();
        return $this->jsonReturn($result);
    }

    public function match()
    {
        $param = request()->param();

        // 初始化变量
        $map = [];
        $sort = 'pingscore desc';
        $is_sql = 0;

        // 获取参数
        $argList = func_get_args();
        // if (!empty($argList)) {
        //     // 查询条件
        //     $map = (isset($argList[0]) && !empty($argList[0])) ? $argList[0] : [];
        //     // 排序
        //     $sort = (isset($argList[1]) && !empty($argList[1])) ? $argList[1] : 'id desc';
        //     // 是否打印SQL
        //     $is_sql = isset($argList[2]) ? isset($argList[2]) : 0;
        // }

        // 常规查询条件
        $param = request()->param();
        if ($param) {

            // if (isset($param['sort']) && $param['sort']) {
            //     $sort = $param['sort']." ".$param["order"];
            // }

            // 筛选名称
            if (isset($param['username']) && $param['username']) {
                $map[] = ['testerName', 'like', "%{$param['username']}%"];
            }
            if (isset($param['type']) && $param['type']) {
                $map[] = ['type', '=', $param['type']];
            }
            // 筛选标题
            if (isset($param['title']) && $param['title']) {
                $map[] = ['title', 'like', "%{$param['title']}%"];
            }

            // 项目
            if (isset($param['projectId']) && $param['projectId']) {
                $map[] = ['projectId', '=', $param['projectId']];
            }

            // 学年
            if (isset($param['gradeId']) && $param['gradeId']) {
                $map[] = ['gradeId', '=', $param['gradeId']];
            }

            // 院系
            if (isset($param['departmentsId']) && $param['departmentsId']) {
                $map[] = ['departmentsId', '=', $param['departmentsId']];
            }

            // 专业
            if (isset($param['professionalId']) && $param['professionalId']) {
                $map[] = ['professionalId', '=', $param['professionalId']];
            }

            // 班级
            if (isset($param['classId']) && $param['classId']) {
                $map[] = ['classId', '=', $param['classId']];
            }

            // 性别
            if (isset($param['gender']) && $param['gender']) {
                $map[] = ['gender', '=', $param['gender']];
            }
            if(isset($param['taskId']) && (int)$param['taskId']){
                $map[] = ['taskId', '=', $param['taskId']];
            }
            if (isset($param['annual']) && $param['annual']) {
                
                $annualResult = $this->annualModel->getInfo($param['annual']);
                $starttime = isset($annualResult['xue_start']) ? trim($annualResult['xue_start']) : '';
                $endtime = isset($annualResult['xue_end']) ? trim($annualResult['xue_end']) : '';
                if ($starttime&&$endtime) {
                    $map[] = ['createdDate', '>= time', $starttime];
                    $map[] = ['createdDate', '<= time', $endtime];
                }
            }
            
            
            
            // 时间
            $starttime = isset($param['starttime']) ? trim($param['starttime']) : '';
            $endtime = isset($param['endtime']) ? trim($param['endtime']) : '';
            if ($starttime&&$endtime) {
                $map[] = ['createdDate', '>= time', $starttime];
                $map[] = ['createdDate', '<= time', $endtime];
            }
        }
        $map[] = ['type', '=', 3];
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }

        $result = $this->model->where($map)->order($sort)->page(0, 11)->column("id");

        // echo $this->model->getLastSql();

        // 打印SQL
        if ($is_sql) {
            echo $this->model->getLastSql();
        }

        $list = [];
        if (is_array($result)) {
            foreach ($result as $val) {
                $info = $this->model->getInfo($val);
                $list[] = $info;
            }
        }


        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list
        );
        return $this->jsonReturn($message);
    }

    //院系画像
    public function yuanxi()
    {
        $departId = (int)input('departmentsId');
        if(empty($departId)){
            $departId = '25';// 默认值计算机专业
        }
        /*$res = DataProf::projectArrList($departId);
        print_r($res);die();*/

        //$prof = \app\admin\model\Professional::where('id',$professionalId)->find();
        $row = \app\admin\model\Departments::where('id',$departId)->find();
        $pmap = [
            'status' => 1,
            'mark' => 1,
            'superior' => $departId,
        ];
        $pcount = \app\admin\model\Clss::where($pmap)->count();
        $total = \app\admin\model\Memb::where($pmap)->count();
        //echo $total;die();
        $umap = [
            'user_type' => 1,
            'mark' => 1,
            'departmentsId' => $departId,
        ];
        $ucount = \app\admin\model\User::where($umap)->count();
        $dmap = [
            'mark'=>1,
            'status' => 1,
            ];
        $dcount = \app\admin\model\Equipment::where($dmap)->count();

        $canyulv = DataProf::projectArrList($departId);

        $hegelv = DataProf::xueyuanArrList($departId);

        $high_weight = DataProf::xueyuanBmi($departId);
        //print_r($high_weight);die();
        $man_level = DataProf::levelAvg($departId);
        $woman_level = DataProf::levelAvg($departId,2);
        $data = [
            'title' => $row?$row['name']:'',
            "total"=> $total, //院系总人数
            'zhuanye_num' => $pcount,
            'teacher_num'=> $ucount,//老师数量
            'device_num' => $dcount,//设备数量
            //
            //学院
            'xueyuan' => DataModel::departxueyuan($departId),
            //各项目参与率
            'canyulv' => [
                'data' => $canyulv[0],
                'yzhou' => $canyulv[1],
            ],
            //各院系成绩合格率
            'hegelv' => [
                'data'=> $hegelv[0],
                'series' => $hegelv[1]
            ],
            //运动时长
            'yundongshichang' => DataProf::ydshichang($departId),
            // 各院系平均分
            'yuanxi_avgs' => DataProf::yuanxiAvg($departId),
            //身高体重BMI
            'high_weight'=>
                [
                    'xueyuan' => $high_weight[0],
                    'weight' => $high_weight[1],
                    'high' => $high_weight[2],
                ],
            'weight' => [
                [ 'value'=> 111, 'name'=>'偏瘦',],
                [ 'value'=> 648, 'name'=>'正常',],
                [ 'value'=> 648, 'name'=>'超重',],
                [ 'value'=> 33, 'name'=>'肥胖',],
            ],
            //男生
            'weight_man' => [
                [ 'value'=> 648, 'name'=>'偏瘦',],
                [ 'value'=> 22, 'name'=>'正常',],
                [ 'value'=> 648, 'name'=>'超重',],
                [ 'value'=> 33, 'name'=>'肥胖',],
            ],
            //女生
            'weight_woman' => [
                [ 'value'=> 648, 'name'=>'偏瘦',],
                [ 'value'=> 22, 'name'=>'正常',],
                [ 'value'=> 648, 'name'=>'超重',],
                [ 'value'=> 6118, 'name'=>'肥胖',],
            ],
            //各院系项目等级
            'project_level' => DataProf::projectLevel($departId),
            //男生各项目平均分与等级
            'man_level' =>
                [
                    'project' => $man_level[0],
                    'data' =>  $man_level[1]
                    /*[
                        [ 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
                        [ 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
                        [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2],
                    ]*/
                ],
            //女生各项目平均分与等级
            'woman_level' =>
                [
                    'project' => $woman_level[0],
                    'data' =>  $woman_level[1]
                ],
        ];
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $data,
        );
        return $this->jsonReturn($message);
    }

    //专业
    public function zhuanye()
    {
        //professionalId
        $departId = (int)input('professionalId');
        if(empty($departId)){
            $departId = '197';// 默认值计算机专业
        }
        /*$res = DataProf::projectArrList($departId);
        print_r($res);die();*/
        //$prof = \app\admin\model\Professional::where('id',$professionalId)->find();
        $row = \app\admin\model\Prof::where('id',$departId)->find();
        $pmap = [
            'status' => 1,
            'mark' => 1,
            'professional' => $departId,
        ];
        $pcount = \app\admin\model\Clss::where($pmap)->count();
        $total = \app\admin\model\Memb::where($pmap)->count();
        //echo $total;die();
      /*  $umap = [
            'user_type' => 1,
            'mark' => 1,
            'professional' => $departId,
        ];
        $ucount = \app\admin\model\User::where($umap)->count();*/
        $ucount = 0;
        $dmap = [
            'mark'=>1,
            'status' => 1,
        ];
        $dcount = \app\admin\model\Equipment::where($dmap)->count();

        $canyulv = DataClasses::projectArrList($departId);

        $hegelv = DataClasses::xueyuanArrList($departId);

        $high_weight = DataClasses::xueyuanBmi($departId);
        //print_r($high_weight);die();
        $man_level = DataClasses::levelAvg($departId);
        $woman_level = DataClasses::levelAvg($departId,2);
        $data = [
            'title' => $row?$row['name']:'',
            "total"=> $total, //院系总人数
            'zhuanye_num' => $pcount,
            'teacher_num'=> $ucount,//老师数量
            'device_num' => $dcount,//设备数量
            //
            //学院
            'xueyuan' => DataModel::profXueyuan($departId),
            //各项目参与率
            'canyulv' => [
                'data' => $canyulv[0],
                'yzhou' => $canyulv[1],
            ],
            //各院系成绩合格率
            'hegelv' => [
                'data'=> $hegelv[0],
                'series' => $hegelv[1]
            ],
            //运动时长
            'yundongshichang' => DataClasses::ydshichang($departId),
            // 各院系平均分
            'yuanxi_avgs' => DataClasses::yuanxiAvg($departId),
            //身高体重BMI
            'high_weight'=>
                [
                    'xueyuan' => $high_weight[0],
                    'weight' => $high_weight[1],
                    'high' => $high_weight[2],
                ],
            'weight' => [
                [ 'value'=> 111, 'name'=>'偏瘦',],
                [ 'value'=> 648, 'name'=>'正常',],
                [ 'value'=> 648, 'name'=>'超重',],
                [ 'value'=> 33, 'name'=>'肥胖',],
            ],
            //男生
            'weight_man' => [
                [ 'value'=> 648, 'name'=>'偏瘦',],
                [ 'value'=> 22, 'name'=>'正常',],
                [ 'value'=> 648, 'name'=>'超重',],
                [ 'value'=> 33, 'name'=>'肥胖',],
            ],
            //女生
            'weight_woman' => [
                [ 'value'=> 648, 'name'=>'偏瘦',],
                [ 'value'=> 22, 'name'=>'正常',],
                [ 'value'=> 648, 'name'=>'超重',],
                [ 'value'=> 6118, 'name'=>'肥胖',],
            ],
            //各院系项目等级
            'project_level' => DataClasses::projectLevel($departId),
            //男生各项目平均分与等级
            'man_level' =>
                [
                    'project' => $man_level[0],
                    'data' =>  $man_level[1]
                    /*[
                        [ 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
                        [ 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
                        [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2],
                    ]*/
                ],
            //女生各项目平均分与等级
            'woman_level' =>
                [
                    'project' => $woman_level[0],
                    'data' =>  $woman_level[1]
                ],
        ];
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $data,
        );
        return $this->jsonReturn($message);
    }




    //班级概览
    public function banji()
    {
        $input = input();
        if(empty($input['classId'])){
            $id = 1057;
        }else{
            $id = (int)$input['classId'];
        }
        $class = \app\admin\model\Clss::get($id);
        if(empty($class)){
            return $this->jsonReturn(message('班级错误',false));
        }
       
        $canyulv = DataModel::projectArrList([['classId', '=', $id]]);

        //DataClass::canyu();die();
        $man_level = DataModel::levelAvg(1);
        $woman_level = DataModel::levelAvg(12);
        $count = DataModel::yundongRate($id);

        $classRankList = DataModel::classRankTime([['classId', '=', $id]]);
        $gradeRankList = DataModel::classRankDis([['classId', '=', $id]]);
        $data = [
            'class_name' => $class['name'],
            //运动总人数
            'yundong_num' => $count[0],
            'zong_num' => $count[1],//总人数
            'yundong_rate' => $count[2],//人数占比
            'man_rate' => $count[3],
            'woman_rate' => $count[4],
            'zong_time'=> $count[5],//运动总时长
            //各项目参与率
            'canyulv' => [
                'data' => $canyulv[0],
                'yzhou' => $canyulv[1],
            ],
            //运动时长
            'yundongshichang' => DataModel::ydshichang(),
              /*  [
                ['time' => '50米短跑','visits' => rand(1,99),'views'=>rand(1,99),],
                ['time' => 'BMI','visits' => rand(1,99),'views'=>rand(1,99),],
                ['time' => '肺活量','visits' => rand(1,99),'views'=>rand(1,99),],
                ['time' => '仰卧起做','visits' => rand(1,99),'views'=>rand(1,99),],
            ],*/
            //参与情况
            'canyun_ting'=> DataClass::canyu([['classId', '=', $id]]),
            //班级运动时长排名
            //运动总时长
            'class_rank1' => $classRankList,
            //跑步总里程
            'class_rank2' => $gradeRankList,
            //肺活量
            'feihuo' => [
                [ 'value'=> 0, 'name'=>'优秀',],
                [ 'value'=> 0, 'name'=>'良好',],
                [ 'value'=> 0, 'name'=>'合格',],
                [ 'value'=> 0, 'name'=>'不合格',],
            ],
            //肺活量 男
            'feihuo_man' => [
                [ 'value'=> 0, 'name'=>'优秀',],
                [ 'value'=> 0, 'name'=>'良好',],
                [ 'value'=> 0, 'name'=>'合格',],
                [ 'value'=> 0, 'name'=>'不合格',],
            ],
            //肺活量 女
            'feihuo_woman' => [
                [ 'value'=> 0, 'name'=>'优秀',],
                [ 'value'=> 0, 'name'=>'良好',],
                [ 'value'=> 0, 'name'=>'合格',],
                [ 'value'=> 0, 'name'=>'不合格',],
            ],
            //身高体重BMI
            'weight_bmi' => [
                [ 'value'=> 0, 'name'=>'偏瘦',],
                [ 'value'=> 0, 'name'=>'正常',],
                [ 'value'=> 0, 'name'=>'超重',],
                [ 'value'=> 0, 'name'=>'肥胖',],
            ],
            //身高体重BMI
            'weight_bmi_man' => [
                [ 'value'=> 0, 'name'=>'偏瘦',],
                [ 'value'=> 0, 'name'=>'正常',],
                [ 'value'=> 0, 'name'=>'超重',],
                [ 'value'=> 0, 'name'=>'肥胖',],
            ],
            //身高体重BMI
            'weight_bmi_woman' => [
                [ 'value'=> 0, 'name'=>'偏瘦',],
                [ 'value'=> 0, 'name'=>'正常',],
                [ 'value'=> 0, 'name'=>'超重',],
                [ 'value'=> 0, 'name'=>'肥胖',],
            ],
            //男生各项目平均分与等级
            'man_level' =>
                [
                    'project' => $man_level[0],
                    'data' =>  $man_level[1]
                ],
            //女生各项目平均分与等级
            'woman_level' =>
                [
                    'project' => $woman_level[0],
                    'data' =>  $woman_level[1]
                ],

        ];

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $data,
        );
        return $this->jsonReturn($message);
    }

    public function students()
    {
        //$this->userId;


        $input = input();
        $row = Db::table('think_user')->where('id',$this->userId)->find();
        if($row['user_type'] == 2 && empty($input['memberId'])){
            $student = \app\admin\model\Member::where('roll',$row['username'])->find();
            $id = $student?$student['id']:0;
        }else{

            //如果未传id，判断是否是学生，是学生传当前登录用户的学生ID
            if(empty($input['memberId'])){
                $id = 49;
            }else{
                $id = $input['memberId'];
            }
        }
        //echo $id;die();
        $memb = \app\admin\model\Memb::get($id);
        if(empty($memb)){
            return $this->jsonReturn(message('学生ID错误',false));
        }
       /* DataModel::projectLevel2($memb);
        die();*/
        $classRankList = DataModel::classRankTime([['classId', '=', $memb['class']]]);
        $gradeRankList = DataModel::classRankDis([['classId', '=', $memb['class']]]);

        $organization = \app\admin\model\School::get($memb['organization']);
        $superior = \app\admin\model\Departments::get($memb['superior']);
        $calss = \app\admin\model\Clss::get($memb['class']);
        $professional = \app\admin\model\Professional::get($memb['professional']);

        $rmap = [];
        if(!empty((int)$input['begin']) && !empty((int)$input['end'])){
            $rmap[] = ['startTime','>', Annual::getTimeArr($input['begin'])[0]];
            $rmap[] = ['endTime','<', Annual::getTimeArr($input['end'])[1]];
        }
        if(!empty($input['tongji'])){
            $rmap[] = ['startTime','>', Annual::getTimeArr($input['tongji'])[0]];
            $rmap[] = ['endTime','<', Annual::getTimeArr($input['tongji'])[1]];
        }
        $rmap[] = ['memberId','=',$id];
        $avg = SportRecord::where($rmap)->whereNotNull('pingscore')->avg('pingscore');




        $goodNum = DataModel::countRaningNum($rmap,1);
        $liangNum = DataModel::countRaningNum($rmap,2);
        $jigeNum = DataModel::countRaningNum($rmap,3);
        $noJigeNum = DataModel::countRaningNum($rmap,0);

        $total = $goodNum+$liangNum+$jigeNum+$noJigeNum;
        $hegeRate = cacl_rate($goodNum+$liangNum+$jigeNum,$total);

        //班级排名
        $where1[] = ['memberId','=',$memb['id']];
        $where2[] = ['classId','=',$memb['class']];


        $classRank = DataModel::sutrank($where1,$where2);
        $where3[] = ['gradeId', '=', $memb['grade']];

        $gradeRank =  DataModel::sutrank($where1,$where3);

        $stuBmi = DataModel::stuBmi([['memberId','=',$memb['id']]]);



        $canyun_ting = \app\admin\model\Data::stuCanyu([['memberId','=',$id]]);

        $data = [
            'name' => $memb['realname'],
            'avatar' => $memb['avatar'],
            'gende' => genderString($memb['gender']),
            'organization' => $organization?$organization['name']:'',
            'superior' => $superior?$superior['name']:'',
            'class' => $calss?$calss['name']:'',
            'professional' => $professional?$professional['name']:'',
            'roll' => $memb['roll'],
            'account' => $memb['username'],
            //成绩概览
            'hegelv' => $hegeRate,
            'score' => (int)$avg.'分',
            'class_rank'=> $classRank,
            'grade_rank' => $gradeRank,
            //身高体重BMI
            'high_bmi' =>[
                'data' => $stuBmi[0],
                'datas'=>  $stuBmi[1],
            ],
            //参与情况
            'canyun_ting'=> [
                'zong_num' => $canyun_ting[0],
                'zong_time' => $canyun_ting[1],
                'zong_avg' => $canyun_ting[2],
                'canyu_data' => $canyun_ting[3],
            ],
            //班级运动时长排名
            //运动总时长
            'class_rank1' =>$classRankList,
            //跑步总里程
            'class_rank2' =>$gradeRankList/*[
                ['id' => 12,'rank'=> 1,'no' => 20230340,'name' => '张小虎1','num' => '32.324',],
                ['id' => 12,'rank'=> 2,'no' => 20230340,'name' => '张小虎2','num' => '32.424',],
                ['id' => 12,'rank'=> 3,'no' => 20230340,'name' => '张小虎2','num' => '32.424',],
                ['id' => 12,'rank'=> 4,'no' => 20230340,'name' => '张小虎2','num' => '32.424',],
                ['id' => 12,'rank'=> 5,'no' => 20230340,'name' => '张小虎2','num' => '32.424',],
            ]*/,
            'class_curr1' => '班级'.$classRank,
            'class_curr2' => '年级'.$gradeRank,
            // 各院系项目平均分
            'project_avgs' => DataModel::projectLevel2($memb)
            /*[
                ['product', '2012', '2013', '2014', '2015', '2016', '2017'],
                ['Milk Tea', 56.5, 82.1, 88.7, 70.1, 53.4, 85.1],
                ['Matcha Latte', 51.1, 51.4, 55.1, 53.3, 73.8, 68.7],
                ['Cheese Cocoa', 40.1, 62.2, 69.5, 36.4, 45.2, 32.5],
                ['Walnut Brownie', 25.2, 37.1, 41.2, 18, 33.9, 49.1]
            ]*/,
            //各项目成绩
            'duanpao'=> [
                'good' => '13.5秒',
                'good_score' => '95',
                'grade_rank' =>'1',
                'class_rank' =>'5',
                'data'=> [
                    [ 'value'=> '35', 'name'=>'优秀',],
                    [ 'value'=> '15', 'name'=>'良好',],
                    [ 'value'=> '25', 'name'=>'合格',],
                    [ 'value'=> '25', 'name'=>'不合格',],
                ],
            ],
            'tiaosheng'=> [
                'good' => '120个',
                'good_score' => '95',
                'grade_rank' =>'1',
                'class_rank' =>'5',
                'data'=> [
                    [ 'value'=> '35', 'name'=>'优秀',],
                    [ 'value'=> '15', 'name'=>'良好',],
                    [ 'value'=> '25', 'name'=>'合格',],
                    [ 'value'=> '25', 'name'=>'不合格',],
                ],
            ],
            'feihuo'=> [
                'good' => '4500ml',
                'good_score' => '95',
                'grade_rank' =>'1',
                'class_rank' =>'5',
                'data'=> [
                    [ 'value'=> '35', 'name'=>'优秀',],
                    [ 'value'=> '15', 'name'=>'良好',],
                    [ 'value'=> '25', 'name'=>'合格',],
                    [ 'value'=> '25', 'name'=>'不合格',],
                ],
            ],
        ];

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $data,
        );
        return $this->jsonReturn($message);
    }

    //跑步下拉项
    public function paobu()
    {
        $arr = [12,14,15,16,17,18,24];
        $list = \app\admin\model\Project::where('id','in',$arr)->field('id,name')->select();
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
        );
        return $this->jsonReturn($message);
    }

    //跳绳下拉项
    public function tiaosheng()
    {
        $arr = [11,13,19,20,21,22,23];
        $list = \app\admin\model\Project::where('id','in',$arr)->field('id,name')->select();
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
        );
        return $this->jsonReturn($message);
    }

    public function duanlian()
    {
        //$list = DataModel::ydsc();

        $qx_yundong_num = DataModel::ticeren();
        $qx_num = \app\admin\model\Memb::allNum();
        $canyu_num = DataModel::ticeren();
        $map1[] = ['gender','=',1];
        $map1+=whereTimeMap();
        $man_rate =  DataModel::ticeren($map1);

        $map2[] = ['gender','=',2];
        $map2+=whereTimeMap();
        $woman_rate = DataModel::ticeren($map2);

        $total = $man_rate+$woman_rate;

        $map3 = whereTimeMap();
        $zong_time = SportRecord::where($map3)->sum('duration');
        $yd_zhanbi = DataModel::yundongZhanbi();
        $data = [
            'qx_yundong_num'=> $qx_yundong_num,//全校运动人数
            'qx_num'=> $qx_num,//全校总人数
            'canyu_num' => $canyu_num,//参与人数
            'no_cany' => $qx_num - $canyu_num,//未参与人数
            'man_rate' => cacl_rate($man_rate,$total),//男女运动比例-男生比例
            'woman_rate' =>  cacl_rate($woman_rate,$total),//男女运动比例-女生比例
            'zong_time' => $zong_time,//运动总时长
            'man_num'=> \app\admin\model\Memb::allNum(1),//男生人数
            'woman_num' => \app\admin\model\Memb::allNum(2),//女生人数
            //各院系运动人数
            'yundong_list' => DataModel::yuanxihYundongNum(),
            //各院系人均运动时长
            'yxrj_avg' => DataModel::ydsc(),
            //各运动占比
            'yd_zhanbi' => [
                'xAxis_data'=>$yd_zhanbi[0],
                'series_data'=>$yd_zhanbi[1],
            ],
            //各运动成绩
            'chengji_zhanbi' => DataModel::ydcjZhanbi(),
        ];
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $data,
        );
        return $this->jsonReturn($message);
    }

}